<?php
// 简单的查询脚本，用于检查订单57的物料计算情况

// 引入ThinkPHP框架
require __DIR__ . '/thinkphp/start.php';

// 定义要查询的订单ID
$orderId = 57;

// 输出查询开始信息
echo "\n=== 订单 {$orderId} 物料计算情况查询 ===\n\n";

// 1. 查询订单基本信息
try {
    $order = \app\admin\model\scanwork\Order::with(['orderModels.model'])->find($orderId);
    if (!$order) {
        echo "订单 {$orderId} 不存在！\n";
        exit;
    }
    
    echo "订单信息：\n";
    echo "- 订单编号：{$order->order_no}\n";
    echo "- 订单名称：{$order->order_name}\n";
    echo "- 客户名称：{$order->customer_name}\n";
    echo "- 创建时间：".date('Y-m-d H:i:s', $order->createtime)."\n";
    echo "- 订单总数量：{$order->total_quantity}\n\n";
    
    // 2. 查询订单包含的产品型号
    if (count($order->orderModels) > 0) {
        echo "订单包含的产品型号：\n";
        foreach ($order->orderModels as $index => $orderModel) {
            $modelName = $orderModel->model ? $orderModel->model->name : '未知型号';
            $productName = $orderModel->model && $orderModel->model->product ? $orderModel->model->product->name : '未知产品';
            echo "- [型号{$index}] {$productName} - {$modelName}：{$orderModel->quantity}件\n";
        }
        echo "\n";
    }
    
    // 3. 查询每个型号的工序物料配置
    echo "各型号的工序物料配置：\n";
    foreach ($order->orderModels as $orderModel) {
        $modelId = $orderModel->model_id;
        $modelName = $orderModel->model ? $orderModel->model->name : '未知型号';
        
        // 查询该型号的工序物料配置
        $processMaterials = \app\admin\model\scanwork\ProcessMaterial::where('model_id', $modelId)
            ->with(['process', 'material'])
            ->select();
        
        echo "型号 {$modelId} ({$modelName}) 共有 {$processMaterials->count()} 个工序物料配置：\n";
        if ($processMaterials->count() > 0) {
            foreach ($processMaterials as $pm) {
                $processName = $pm->process ? $pm->process->name : '未知工序';
                $materialName = $pm->material ? $pm->material->name : '未知物料';
                echo "  - 工序：{$processName}，物料：{$materialName}，单件用量：{$pm->quantity}，损耗率：{$pm->loss_rate}%\n";
            }
        } else {
            echo "  - 暂无工序物料配置\n";
        }
    }
    echo "\n";
    
    // 4. 查询订单物料需求结果
    $orderMaterials = \app\admin\model\scanwork\OrderMaterial::with(['material', 'supplier'])
        ->where('order_id', $orderId)
        ->select();
    
    echo "订单物料需求计算结果：\n";
    echo "共有 {$orderMaterials->count()} 个物料需求记录\n";
    if ($orderMaterials->count() > 0) {
        foreach ($orderMaterials as $om) {
            $materialName = $om->material ? $om->material->name : '未知物料';
            $supplierName = $om->supplier ? $om->supplier->name : '未指定供应商';
            echo "- 物料：{$materialName}，需求数量：{$om->required_quantity}，预估单价：{$om->estimated_price}，预估金额：{$om->estimated_amount}，供应商：{$supplierName}\n";
        }
    }
    echo "\n=== 查询完成 ===\n";
    
} catch (Exception $e) {
    echo "查询出错：".$e->getMessage()."\n";
    echo "错误位置：".$e->getFile().":".$e->getLine()."\n";
    echo "堆栈信息：".$e->getTraceAsString()."\n";
}

?>